from lark import Lark
from collections import ChainMap
from typing import ChainMap as tChainMap, Dict, Union

from grammar import Grammar


class Parser:

    def __init__(self, grammar="", context: Union[tChainMap, Dict] = None):
        self.grammar = Grammar(grammar)
        self.context = context
        self.parser = Lark(self.grammar.grammar, parser="lalr")

    def set_parser(self, parser):
        self.parser = parser

    def parse(self, text, context: Union[ChainMap, Dict] = None):
        if context:
            context = ChainMap(context, self.context)
        if isinstance(context, (ChainMap, Dict)):
            return self.parser.parse(text, **context)
        return self.parser.parse(text)
